package com.mmlc.meimei.lichengkongjian.mine;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidnetframe.BaseParentActivity;
import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.requestbean.BaseResponseBean;
import com.androidnetframe.responsejavabean.RequestError;
import com.androidnetframe.utils.LogUtils;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.App;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.network.filter.ReportRequestFilter;
import com.mmlc.network.filter.UploadImgRequestFilter;
import com.mmlc.network.responsebean.ReportReasonListResponse;
import com.mmlc.utils.ImageTools;
import com.mmlc.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by Administrator on 2016/12/8.
 */

public class ActivitySuggest  extends InterActivity{

    @InjectView(R.id.iv_back)
    ImageView ivBack;
    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.et_reason)
    EditText etReason;
    @InjectView(R.id.iv_post)
    ImageView ivPost;
    @InjectView(R.id.iv_a)
    ImageView iv_a;
    @InjectView(R.id.iv_b)
    ImageView iv_b;
    @InjectView(R.id.iv_c)
    ImageView iv_c;
    @InjectView(R.id.iv_d)
    ImageView iv_d;
    @InjectView(R.id.rr_a)
    RelativeLayout rr_a;
    @InjectView(R.id.rr_b)
    RelativeLayout rr_b;
    @InjectView(R.id.rr_c)
    RelativeLayout rr_c;
    @InjectView(R.id.rr_d)
    RelativeLayout rr_d;
    @InjectView(R.id.iva_delete)
    ImageView ivaDelete;
    @InjectView(R.id.ivb_delete)
    ImageView ivbDelete;
    @InjectView(R.id.ivc_delete)
    ImageView ivcDelete;
    @InjectView(R.id.ivd_delete)
    ImageView ivdDelete;
    @InjectView(R.id.tv_submit)
    TextView tvSubmit;

    @Override
    protected int initContentView() {
        return R.layout.activity_suggest;
    }

    @Override
    protected void initView() {
        ButterKnife.inject(this);
        initUI();
    }

    private ArrayAdapter<String> arr_adapter;
    private List<String> data_list;
    private HashMap<RelativeLayout,String> picPath_list;
    private HashMap<RelativeLayout,String> picMap;
    private ArrayList<ImageView> img_list = new ArrayList<>();
    private ArrayList<RelativeLayout> rr_list = new ArrayList<>();
    private ReportReasonListResponse response;

    private void initUI() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tvTitle.setText("意见反馈");

        img_list.add(iv_a);
        img_list.add(iv_b);
        img_list.add(iv_c);
        img_list.add(iv_d);

        rr_list.add(rr_a);
        rr_list.add(rr_b);
        rr_list.add(rr_c);
        rr_list.add(rr_d);

        // 新建一个可以添加属性的文本对象
        SpannableString ss = new SpannableString("在此描述详细问题");
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(14,true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        etReason.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失

        picPath_list = new HashMap<>();
        picMap = new HashMap<>();

    }


    @OnClick(R.id.iv_post)
    public void Onclick(){
        imageSelector(4-picPath_list.size());
    }


    public static final int REQUEST_IMAGE =100;

    private void imageSelector(int picnums) {
        ArrayList<String> defaultDataArray =  new ArrayList<>();
        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        // 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, picnums);
        // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        // 默认选择图片,回填选项(支持String ArrayList)
        intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, defaultDataArray);
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    //照片缩小的比例
    private static final int SCALE = 2;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.e("onActivityResult","------"+requestCode+"----"+requestCode);

        if(requestCode == REQUEST_IMAGE&& resultCode ==RESULT_OK && data!=null){
            List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            ContentResolver contentResolver = getContentResolver();
            int currentLen = picPath_list.size();
            for (int i = 0; i < path.size(); i++) {
                LogUtils.e("选择的图片uri", path.get(i));
                Bitmap bitmap = BitmapFactory.decodeFile(path.get(i));
                if (bitmap != null) {
                    Bitmap smallBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
                    bitmap.recycle();
                    img_list.get(i).setImageBitmap(smallBitmap);
                    rr_list.get(i).setVisibility(View.VISIBLE);
                    //将处理过的图片保存到本地
                    String currentHeadPhoto = ImageTools.savePhotoToSDCard(smallBitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis()));
                    picPath_list.put(rr_list.get(i),currentHeadPhoto);
                    picMap.put(rr_list.get(i),currentHeadPhoto);
                }
            }
            for (int i = 0; i < path.size(); i++) {
                img_list.remove(0);
                rr_list.remove(0);
            }
            if (picPath_list.size()==4){
                ivPost.setVisibility(View.GONE);
            }
        }
    }

    @OnClick({R.id.iva_delete,R.id.ivb_delete,R.id.ivc_delete,R.id.ivd_delete})
    public void delete(View view){
        switch (view.getId()){
            case R.id.iva_delete:
                rr_a.setVisibility(View.GONE);
                picPath_list.remove(rr_a);
                picMap.remove(rr_a);
                img_list.add(iv_a);
                rr_list.add(rr_a);
                break;
            case R.id.ivb_delete:
                rr_b.setVisibility(View.GONE);
                picPath_list.remove(rr_b);
                picMap.remove(rr_b);
                img_list.add(iv_b);
                rr_list.add(rr_b);
                break;
            case R.id.ivc_delete:
                rr_c.setVisibility(View.GONE);
                picPath_list.remove(rr_c);
                picMap.remove(rr_c);
                img_list.add(iv_c);
                rr_list.add(rr_c);
                break;
            case R.id.ivd_delete:
                rr_d.setVisibility(View.GONE);
                picPath_list.remove(rr_d);
                picMap.remove(rr_d);
                img_list.add(iv_d);
                rr_list.add(rr_d);
                ivPost.setVisibility(View.VISIBLE);
                break;
        }
        if(picPath_list.size()<4){
            ivPost.setVisibility(View.VISIBLE);
        }
    }
    public  int id=1;
    public  int time=0;
    @OnClick(R.id.tv_submit)
    public void sub(){
        time = 0;
        stringBuffer = new StringBuffer();

        if(TextUtils.isEmpty(etReason.getText().toString().trim())){
            ToastUtils.showToast("请描述详细问题");
            return;
        }
        if(etReason.getText().toString().trim().length()<15){
            ToastUtils.showToast("问题描述不得少于15字");
            return;
        }
        if(!App.user.getLoginState()){
            ToastUtils.showToast("请先登录");
            return;
        }

        //提交举报信息
        submitReport();

    }


    public boolean flag=true;
    public StringBuffer stringBuffer = new StringBuffer();
    public Handler mHandler;

    private void submitReport() {
        //handler用于处理图片上传是否完成
        mHandler = new Handler(){
            public int i=0;
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == 0){
                    i++;
                    if(i == picMap.size()){
                        commitInfo(new String(stringBuffer));
                    }
                }
            }
        };
        final String str ="";
        if(picMap.size()!=0){
            for (String v : picMap.values()) {
                //先上传图片
                commitPhoto(v);
                //再获取服务器返回的图片地址
            }
        }else {
            commitInfo(str);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
        }

        //删除压缩保存在本地的图片
        if(picMap.size()!=0){
            for (String v : picMap.values()) {
                File file = new File(v);
                if(file.exists() && file.isFile()){
                    file.delete();
                }
            }
        }
    }

    private void commitPhoto(final String tmpheader) {
        UploadImgRequestFilter imgFilter = new UploadImgRequestFilter((BaseParentActivity)activity);
        imgFilter.requestParams.addBodyParameter("imgFile", new File(tmpheader));
        imgFilter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e(TAG, "onSuccess: "+result );
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject data = jsonObject.getJSONObject("data");
                    stringBuffer.append(data.optString("path")+",");
                    mHandler.sendEmptyMessage(0);
                    time++;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess.toString());
            }
        });
    }


    public  void commitInfo(String str){
        ReportRequestFilter filter = new ReportRequestFilter((BaseParentActivity) activity);
        filter.requestBean.content = etReason.getText().toString();
        filter.requestBean.imgs = str;
        filter.requestBean.type = 0;
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<BaseResponseBean>() {
            @Override
            public void onSuccess(BaseResponseBean result) {
                ToastUtils.showToast("反馈成功");
                finish();
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess.toString());
            }
        });
    }
}
